How it works: The index j iterates through all elements before i.
For every pair (j, i), we calculate the diff.
If any arithmetic sequences already ended at j with that same diff,
extending them to i creates valid sequences of length 3 or more.
def numberOfArithmeticSlices(nums):
total = 0
dp = [collections.defaultdict(int) for _ in nums]
for i in range(len(nums)):
for j in range(i):
diff = nums[i] - nums[j]
count_at_j = dp[j][diff]
total += count_at_j
dp[i][diff] += count_at_j + 1
return total
int numberOfArithmeticSlices(vector<int>& nums) {
int n = nums.size(); long long total_count = 0;
vector<unordered_map<long long, int>> dp(n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
long long diff = (long long)nums[i] - nums[j];
int count_at_j = dp[j].count(diff) ? dp[j][diff] : 0;
total_count += count_at_j;
dp[i][diff] += (count_at_j + 1);
}
}
return (int)total_count;
}